package com.yanx.system.base.infra.mapper;

import com.yanx.system.base.domain.entity.SysRole;
import com.yanx.system.base.domain.entity.rel.SysRoleDept;
import com.yanx.system.base.domain.entity.rel.SysRoleMenu;
import com.yanx.system.base.model.dto.SysRoleDto;
import org.mapstruct.*;
import org.mapstruct.factory.Mappers;

/**
 * 菜单权限 实体转换类
 *
 * @author: gotanks
 * @create: 2023-2-10
 */
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE,
        nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface SysRoleMapper {

    SysRoleMapper INSTANCE = Mappers.getMapper(SysRoleMapper.class);

    SysRole toSysRole(SysRoleDto dto);

    @Mapping(target = "roleMenus", source = "menuIds")
    @Mapping(target = "roleDepts", source = "deptIds")
    SysRole toSysRole(SysRoleDto dto, @MappingTarget SysRole entity);

    static SysRoleMenu toSysRoleMenu(Long menuId) {
        SysRoleMenu sysRoleMenu = new SysRoleMenu();
        sysRoleMenu.setMenuId(menuId);
        return sysRoleMenu;
    }

    static SysRoleDept toSysRoleDept(Long deptId) {
        SysRoleDept sysRoleDept = new SysRoleDept();
        sysRoleDept.setDeptId(deptId);
        return sysRoleDept;
    }

    @AfterMapping
    static void afterToSysRole(SysRoleDto dto, @MappingTarget SysRole entity) {
        Long roleId = dto.getId();
        if (entity.getRoleMenus() != null) {
            entity.getRoleMenus().forEach(t -> t.setRoleId(roleId));
        }
        if (entity.getRoleDepts() != null) {
            entity.getRoleDepts().forEach(t -> t.setRoleId(roleId));
        }
    }

}
